/*
   Copyright (C) 2006
   Andrew Madigan

This file is part of nhttpd.

nhttpd is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

nhttpd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with nhttpd; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.
*/

#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include <nhttpd/bufreader.h>
#include <nhttpd/string.h>
#include <nhttpd/readahead.h>
#include <stdbool.h>
#include <nhttpd/list.h>
#include <nhttpd/hashtable.h>
#include <nhttpd/http.h>
#include <nhttpd/request.h>

#define SWITCH_STR2(VAR, VAR2, VAL) SWITCH_STR(VAR, VAR2, VAL, # VAL)
#define SWITCH_STR(VAR, VAR2, VAL, STR) if (strcmp(VAR, STR) == 0) \
			VAR2 = VAL


void HRQ_ReadRequestLine(HTTP_Request* restrict self)	{
	//First pass, grab line
	String* line = RA_ReadLine(self->reader);
	STR_Trim(line);
	
	
	
	//Second pass, break into three main parts
	if (line->length)	{
		List* parts = STR_Tokenize(line, " ");
		if (parts->head)	{
			self->method_string = STR_ToCStr(parts->head->val);
			if (parts->head->next)	{
				self->request_string = STR_ToCStr(parts->head->next->val);
				if (parts->head->next->next)	{
					self->version_string = STR_ToCStr(parts->head->next->next->val);
				}
			}
		}
		O_Free(parts);
	}
	
	O_Free(line);

	//Third pass, break request_string into uri and query_string
	if (self->request_string)	{
		const char* pos = index(self->request_string, '?');
		if (pos)	{
			const int qindex = pos - self->request_string;
			String* request_str = STR_CreateCStr(self->request_string);
			self->uri = STR_ToCStrFree(STR_Substring(request_str,0, qindex));
			self->query_string = STR_ToCStrFree(STR_Substring(request_str,
										qindex + 1, request_str->length - qindex - 1));
			O_Free(request_str);
		}
		else	{
			self->uri = self->request_string;
		}
	}
	
}

void HRQ_ReadHeaders(HTTP_Request* restrict self)	{
	String* line = RA_ReadLine(self->reader);
	char* name;
	String* value;
	List* list;
	int index;
	
	if (line != NULL) STR_Trim(line);
	
	while (line != NULL && line->length)	{
		index = STR_IndexOf(line, ':');
		if (index == -1) continue;
		
		name = STR_ToCStrFree(STR_Substring(line, 0, index));
		value = STR_Substring(line, index + 1, line->length - index - 1);
		
		list = HT_Get(self->headers, name);
		
		if (!list)	{
			list = L_Create();
			HT_Put(self->headers, name, list);
		}
		
		L_Add(list, STR_ToCStrFree(value));
		O_Free(line);
		line = RA_ReadLine(self->reader);
		if (line) STR_Trim(line);
	}
	if (line != NULL) O_Free(line);
}

void HRQ_ReadExtra(HTTP_Request* restrict self)	{
	self->parameters = HT_Create(true, true);
	//Fourth pass, break query_string into name, value pairs
	if (self->query_string)	{
		String* tempstr = STR_CreateCStr(self->query_string);
		List* parts = STR_Tokenize(tempstr, "&");
		O_Free(tempstr);
		ListIter* iter = LI_Create(parts);
		int eindex;
		String* entry;
		while (LI_Next(iter))	{
			entry = LI_GetValue(iter);
			eindex = STR_IndexOf(entry, '=');
			if (eindex == -1)	{
				HT_Put(self->parameters, STR_ToCStr(entry), strdup(""));
			}
			else	{
				HT_Put(self->parameters,STR_ToCStrFree(STR_Substring(entry, 
						 0, eindex)), STR_ToCStrFree(STR_Substring(entry, eindex + 1, 
						 entry->length - eindex - 1)));
			}
		}
		O_Free(iter);
		O_Free(parts);
	}
	
	//Fifth pass, translate some stringed values into enumed forms
	if (self->method_string)	{
		SWITCH_STR2(self->method_string, self->method, OPTIONS);
		SWITCH_STR2(self->method_string, self->method, GET);
		SWITCH_STR2(self->method_string, self->method, HEAD);
		SWITCH_STR2(self->method_string, self->method, POST);
		SWITCH_STR2(self->method_string, self->method, PUT);
		SWITCH_STR2(self->method_string, self->method, DELETE);
		SWITCH_STR2(self->method_string, self->method, TRACE);
		SWITCH_STR2(self->method_string, self->method, CONNECT);
		SWITCH_STR2(self->method_string, self->method, EXTENSION);
	}
	
	if (self->version_string == NULL) self->version = HTTP_09;
	else	{
		SWITCH_STR(self->version_string, self->version, HTTP_09, "");
		else SWITCH_STR(self->version_string, self->version, HTTP_10, "HTTP/1.0");
		else SWITCH_STR(self->version_string, self->version, HTTP_09, "HTTP/1.1");
		else self->version=UNKNOWN;
	}
}

void HRQ_ReadRequest(HTTP_Request* restrict self)	{
	if (!RA_isInstance(self->reader)) self->reader = RA_Create(self->reader);
	HRQ_ReadRequestLine(self);
	HRQ_ReadHeaders(self);
}
			
void HRQ_Free(void* restrict _self)	{
	HTTP_Request* self = _self;
	O_Free(self->headers);
	if (self->parameters != NULL) O_Free(self->parameters);
	if (self->cookies != NULL) O_Free(self->cookies);
	free(self->session);
	free(self->method_string);
	free(self->version_string);
	if (self->uri != self->request_string) free(self->request_string);
	free(self->uri);
	free(self->query_string);
	O_Free(self->reader);
	free(self);
}

const Class HTTP_RequestClass = {HRQ_Free};

HTTP_Request* HRQ_Create(Socket* restrict socket)	{	
	HTTP_Request* self = malloc(sizeof(HTTP_Request));
	self->super.methods = &HTTP_RequestClass;
	self->headers = HT_Create(true, true);
	self->headers->Free = OFreeP;
	self->parameters = NULL;
	self->cookies = NULL;
	self->session = NULL;
	self->method_string = NULL;
	self->version_string = NULL;
	self->request_string = NULL;
	self->uri = NULL;
	self->query_string = NULL;
	self->method = 0;
	self->version = 0;
	self->socket = socket;
	self->reader = SO_GetReader(socket);
	self->reader = BR_Create(self->reader);
	HRQ_ReadRequest(self);
	return self;
}

#ifdef NH_REQUEST_TEST
HTTP_Request* HRQ_CreateRdr(Reader* restrict reader)	{
	static const Class HTTP_RequestClass = {HRQ_Free};
	HTTP_Request* self = malloc(sizeof(HTTP_Request));
	self->super.methods = &HTTP_RequestClass;
	self->headers = HT_Create(true, true);
	self->headers->Free = OFreeP;
	self->parameters = NULL;
	self->cookies = NULL;
	self->session = NULL;
	self->method_string = NULL;
	self->version_string = NULL;
	self->request_string = NULL;
	self->uri = NULL;
	self->query_string = NULL;
	self->method = 0;
	self->version = 0;
	self->socket = NULL;
	self->reader = reader;
	self->reader = BR_Create(self->reader);
	HRQ_ReadRequest(self);
	return self;
}
#endif

void HRQ_flatten_Append(String* buf, char* app)	{
	if (app == NULL)	{
		int len = -1;
		STR_AppendBuf(buf, (char*) &len, sizeof(int) / sizeof(char));
	}
	else {
		int len = strlen(app);
		STR_AppendBuf(buf, (char*) &len, sizeof(int) / sizeof(char));
		STR_AppendBuf(buf, app, len);
	}
}

void HRQ_flatten_List(String* buf, List* li) {
	int count = li->length;
	STR_AppendBuf(buf, (char*) &count, sizeof(int) / sizeof(char));
	ListIter* iter = LI_Create(li);
	while (LI_Next(iter)) {
		HRQ_flatten_Append(buf, LI_GetValue(iter));
	}
	O_Free(iter);
}
	
void HRQ_flatten_Hashtable(String* buf, Hashtable* ht)	{
	int count = ht->count;
	STR_AppendBuf(buf, (char*) &count, sizeof(int) / sizeof(char));
	HT_Iterator* iter = HTI_Create(ht);
	while (HTI_Next(iter))	{
		HRQ_flatten_Append(buf, HTI_GetKey(iter));
		HRQ_flatten_List(buf, HTI_GetValue(iter));
	}
	O_Free(iter);
}

String* HRQ_Flatten(HTTP_Request* self)	{
	String* buf = STR_Create();
	HRQ_flatten_Append(buf, self->method_string);
	HRQ_flatten_Append(buf, self->request_string);
	HRQ_flatten_Append(buf, self->uri);
	HRQ_flatten_Append(buf, self->query_string);
	HRQ_flatten_Append(buf, self->version_string);
	HRQ_flatten_Append(buf, STR_ToCStrFree(SO_Flatten(self->socket)));
	int chi = RA_GetNext(self->reader);
	char* remaining = BR_GetRemaining(RA_GetChild(self->reader));
	int len = strlen(remaining);
	if (chi != -1)	{
		len++;
		STR_AppendBuf(buf, (char*) &len, sizeof(int) / sizeof(char));
		STR_Append(buf, chi);
	}
	else	{
		STR_AppendBuf(buf, (char*) &len, sizeof(int) / sizeof(char));
	}
	STR_AppendBuf(buf, remaining, len);
	free(remaining);
	HRQ_flatten_Hashtable(buf, self->headers);
	
	return buf;
}

char* HRQ_unflatten_String(char* src, int* index)	{
	int len;
	memcpy(&len, src + *index, sizeof(int));
	(*index) += sizeof(int) / sizeof(char);
	if (len == -1) return NULL;
	if (!len) return strdup("");
	char* rv = calloc(len + 1, sizeof(char));
	memcpy(rv, src + *index, len);
	memset(rv + len, 0, 1);
	*index += len;
	return rv;
}

List* HRQ_unflatten_List(char* src, int* index) {
	List* rv = L_Create();
	int entries;
	memcpy(&entries, src + *index, sizeof(int) / sizeof(char));
	*index += sizeof(int) / sizeof(char);
	for (int i = 0; i < entries; i++) {
		L_Add(rv, HRQ_unflatten_String(src, index));
	}
	return rv;
}

Hashtable* HRQ_unflatten_Hashtable(char* src, int* index)	{
	Hashtable* rv = HT_Create(true, true);
	int entries;
	memcpy(&entries, src + *index, sizeof(int) / sizeof(char));
	*index += sizeof(int) /sizeof(char);
	char* key;
	List* values;
	for (int i = 0; i < entries; i++)	{
		key = HRQ_unflatten_String(src, index);
		values = HRQ_unflatten_List(src,index);
		HT_Put(rv, key, values);
	}
	return rv;
}

HTTP_Request* HRQ_Unflatten(char* src, int fd)	{
	HTTP_Request* self = malloc(sizeof(HTTP_Request));
	self->super.methods = &HTTP_RequestClass;
	int index = 0;
	self->method_string = HRQ_unflatten_String(src, &index);
	self->request_string = HRQ_unflatten_String(src, &index);
	self->uri = HRQ_unflatten_String(src, &index);
	self->query_string = HRQ_unflatten_String(src, &index);
	self->version_string = HRQ_unflatten_String(src, &index);
	char* socket = HRQ_unflatten_String(src, &index);
	self->socket = SO_Unflatten(fd, socket);
	free(socket);
	Reader* bufreader = BR_Create(SO_GetReader(self->socket));
	char* buf = HRQ_unflatten_String(src, &index);
	if (buf) {
		BR_SetBuffer(bufreader, buf);
		free(buf);
	}
	
	self->headers = HRQ_unflatten_Hashtable(src, &index);

	self->parameters = NULL;
	self->cookies = NULL;
	self->session = NULL;
	self->method = 0;
	self->version = 0;
	return self;
}

#ifdef NH_REQUEST_TEST

#include <nhttpd/writer.h>
#include <fcntl.h>

#define COMP(val) \
	printf("Original: %s\t Recovered: %s\n", orig->val, recov->val)

int main(int argc, char* argv[]) {
	HTTP_Request* orig = HRQ_CreateRdr(RD_Create(0));
	printf("Read\n");
	
	HT_Iterator* ohead = HTI_Create(orig->headers);
	List* list;
	ListIter* iter;
	printf("Headers\n");
	while (HTI_Next(ohead)) {
		list = HTI_GetValue(ohead);
		iter = LI_Create(list);
		while (LI_Next(iter)) {
			printf("%s:%s\n", HTI_GetKey(ohead), LI_GetValue(iter));
		}
		O_Free(iter);
	}
	
	String* flattened = HRQ_Flatten(orig);
	printf("Flattened: %d\n", flattened->length);
	char* flattenedStr = STR_ToCStr(flattened);
	
	HTTP_Request* recov = HRQ_Unflatten(flattenedStr, orig->reader);
	printf("Unflattened\n");
	
	COMP(method_string);
	COMP(request_string);
	COMP(uri);
	COMP(query_string);
	COMP(version_string);
	
	printf("Headers:\n");
	printf("Original: %d\t Recovered: %d\n", orig->headers->count,
		recov->headers->count);
	HT_Iterator* rhead = HTI_Create(recov->headers);
	
	printf("Recovered Headers\n");
	while (HTI_Next(rhead)) {
		list = HTI_GetValue(rhead);
		iter = LI_Create(list);
		while (LI_Next(iter)) {
			printf("%s:%s\n", HTI_GetKey(rhead), LI_GetValue(iter));
		}
		O_Free(iter);
	}
	
	return 0;
}
#endif
